package com.MediaVaultTest;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import com.MediaVaultTest.PMF;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.apphosting.utils.remoteapi.RemoteApiPb.Request;

public class uploadFormat extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

        Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
        BlobKey blobKey = blobs.get("myFile");
        
      //Get user currently logged in
      PersistenceManager pm = PMF.get().getPersistenceManager();
      UserService userService = UserServiceFactory.getUserService();
      User user = userService.getCurrentUser();
      String userEmail = user.getEmail();
      UserStore userStore = null;
		 Key key = KeyFactory.createKey(UserStore.class.getSimpleName(), userEmail);
		 try { 
			 userStore = pm.getObjectById(UserStore.class, key);
			 //See if anything is returned\
		 } catch (JDOObjectNotFoundException e) {
			 userStore = null;
		 }
        
        if (blobKey == null) {
            res.sendRedirect("/");
        } else {
        	//Setup factories
        	 BlobInfo blobInfo;
        	 BlobInfoFactory blobInfoFactory = new BlobInfoFactory();
        	 blobInfo = blobInfoFactory.loadBlobInfo(blobKey);
        	 Long Size = blobInfo.getSize();
        	 String mediaType = blobInfo.getContentType();
        	 String Title = blobInfo.getFilename();
        	 String stringMedia = req.getParameter("media");
        	 
        	//Add File to user
        	 try{
        		 //little setup
	        	 
	        	 Key stringkey = KeyFactory.stringToKey(stringMedia);
	        	 //Format, media and userstore
	        	 Format format = new Format(blobKey, Size, mediaType);
	        	 Media media = pm.getObjectById(Media.class, stringkey);
				 UserStore mediauserStore = media.getUserStore();
				 if(userStore==null||!mediauserStore.equals(userStore)){
					 res.sendRedirect("/index.jsp?msg=Unlucky");
				 }
	        	 //Check size
	        	 QuotaLogic quotaLogic = new QuotaLogic();
	        	 long uploadSize = quotaLogic.getUploadQuota();
	         	 long stoargeSize = quotaLogic.getStorageQuota();
	        	 if(uploadSize>(userStore.getmbUpload()+Size)&&stoargeSize>(userStore.getmbStorage()+Size)){
	    			 
	    			 media.addFormat(format);
	    			
	    			 //update quotas
	    			 userStore.setmbUpload(userStore.getmbUpload()+Size);
	    			 userStore.setmbStorage(userStore.getmbStorage()+Size);
				 } else {
					 //Insufficent data delete file
					 blobstoreService.delete(blobKey);
				 }
	        	pm.close();
        	 } finally {
        		 //nothing
        	 }
            res.sendRedirect("/viewInfo.jsp?key="+stringMedia);
        }
    }
}
